package graph.outils.io;

import graph.drawings.EdgeDrawing;
import graph.drawings.GraphDrawing;
import graph.drawings.VertexDrawing;

import java.io.File;
import java.util.Collection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class GraphOutput {
	public void writeMatrix(String filePath) {

	}

	public static void writeXmlFile(String filePath, GraphDrawing graphDrawing) {
		try {

			DocumentBuilderFactory docFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

			// root elements
			Document doc = docBuilder.newDocument();
			Element rootElement = doc.createElement("Graph");
			doc.appendChild(rootElement);

			Element vertexsElement = doc.createElement("Vertexs");
			rootElement.appendChild(vertexsElement);

			Collection<VertexDrawing> vertexs = graphDrawing.getVertexs();
			for(VertexDrawing v : vertexs) {
				Element element = doc.createElement("Vertex");
				
				element.setAttribute("X", String.valueOf(v.getPosition().getX()));
				element.setAttribute("Y", String.valueOf(v.getPosition().getY()));
				element.setAttribute("Key", v.getKey());

				vertexsElement.appendChild(element);
			}
			
			Element edgesElement = doc.createElement("Edges");
			rootElement.appendChild(edgesElement);
			
			Collection<EdgeDrawing> edges = graphDrawing.getEdges();
			for(EdgeDrawing ed : edges) {
				Element element = doc.createElement("Edge");
				
				element.setAttribute("Value", String.valueOf(ed.getValue()));
				element.setAttribute("From", ed.getStartVertex().getKey());
				element.setAttribute("To", ed.getEndVertex().getKey());

				edgesElement.appendChild(element);
			}
			

			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File(filePath));
			transformer.transform(source, result);

		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (TransformerException tfe) {
			tfe.printStackTrace();
		}
	}
}
